package com.lfg.leetcode.leetcode0;

/**
 *
 */
public class KMP2 {

    public static int[] getNext(String content) {
        int length = content.length();
        int[] next = new int[length];
        next[0] = -1;
        int k = -1;
        for (int j = 0; j < length - 1; ) {
            if (k == -1 || content.charAt(k) == content.charAt(j)) {
                ++j;
                ++k;
                if (content.charAt(j) == content.charAt(k)) {
                    next[j] = next[k];
                } else {
                    next[j] = k;
                }
            } else {
                k = next[k];
            }
        }
        return next;
    }

    public static String match(String str, String modeStr) {
        int[] next = getNext(modeStr);
        int i = 0, j = 0;
        while (i < str.length() && j < modeStr.length()) {
            if (j == -1 || str.charAt(i) == modeStr.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }
        if (j >= modeStr.length()) {
            return str.substring(i - modeStr.length(), i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] ret = getNext2("abcabd");
        for (int i : ret) {
            System.out.print(i + ", ");
        }
        System.out.print(match("aaaaaabcabd", "abcabd"));
    }


    public static int[] getNext2(String content) {
        int[] next = new int[content.length()];
        next[0] = -1;
        int j = -1;
        for (int i = 0; i < content.length() - 1 && j < content.length() - 1; ) {
            if (j == -1 || content.charAt(i) == content.charAt(j)) {
                ++i;
                ++j;
                if (content.charAt(i) == content.charAt(j)) {
                    next[i] = next[j];
                } else {
                    next[i] = j;
                }
            } else {
                j = next[j];
            }
        }
        return next;
    }
}
